# -- coding: utf-8 --
# encoding: utf-8
# !/usr/local/bin/python3

"""
@author: Gao Shuo
@contact: dorothy400@163.com
@software: PyCharm
@file: clip_multi_path.py
@time: 2020/5/6 11:03
200506王腾发来有各级子文件夹的标注图
input: 原图片存放目录，裁剪后标注图片存放目录，裁剪后原图存放目录
output: 标注图与原图裁剪后结果
"""

import os.path
import sys
import cv2
from PIL import Image
import sys
import numpy as np
sys.path.append("..")
from functions import new_folder

if __name__ == "__main__":
    path_ori = sys.argv[1]
    dest_01_clip = new_folder(sys.argv[2])
    dest_ori_clip = new_folder(sys.argv[3])
    ext = ".jpg"
    ext_label = ".png"
    ori_imgs=[]
    label_imgs=[]
    target_width = 800
    target_height = 480

    li1 = os.listdir(path_ori) # rys 学生
    for path1 in li1:
        path1_os = os.path.join(path_ori, path1)
        li2 = os.listdir(path1_os)# 图片名1
        # 读取原图和标注后的图
        for path2 in li2:
            path2_os = os.path.join(path1_os, path2)
            li3 = os.listdir(path2_os)
            jpg_name = [x for x in li3 if ext in x and x.split(ext)[1] == ""] # 图片
            if len(jpg_name)  != 1 :
                print "================不正常的目录================"
                print path2_os
            else:
                path3_os = os.path.join(path2_os, jpg_name[0])
                ori_imgs.append(path3_os)
                path_label = path3_os.replace( "200506/标注结果","200506/标注结果_label").replace(ext,ext_label)
                label_imgs.append(path_label)
                # print path_label
                # print len(ori_imgs)
    for index, path_ori in enumerate(ori_imgs):
        im_ori = Image.open(path_ori)
        im_label = Image.open(label_imgs[index])
        size = im_ori.size
        n_width = size[0] / target_width
        n_height = size[1] / target_height
        filepath ='_'.join( label_imgs[index].split('/')[-3:]) # 取后三个
        for i in range(n_width):
            for j in range(n_height):
                image_ori = im_ori.crop((target_width * i, target_height * j,
                                         target_width * (i + 1), target_height * (j + 1)))
                image_label = im_label.crop((target_width * i, target_height * j,
                                         target_width * (i + 1), target_height * (j + 1)))
                image_label1 = np.array(image_label)
                num = np.sum(image_label1 == 1)
                if num > 0:
                    print(label_imgs[index])
                    image_ori.save(os.path.join(dest_ori_clip, filepath + '_' + str(i) + '_' + str(j) + '.png'))
                    image_label.save(os.path.join(dest_01_clip, filepath + '_' + str(i) + '_' + str(j) + '.png'))











